package ru.st.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import ru.st.selenium.model.Film;

public class InternalPage extends AnyPage {

	public InternalPage(PageManager pages) {
		super(pages);
	}
	
  public InternalPage ensurePageLoaded() {
    super.ensurePageLoaded();
    wait.until(presenceOfElementLocated(By.cssSelector("nav")));
    return this;
  }
 
  public InternalPage ensureMoviesLoaded() {
	    super.ensureMoviesLoaded();
	    wait.until(presenceOfElementLocated(By.className("nocover")));
	    return this;
	  }
  
  public InternalPage ensurePageReloaded() {
	    super.ensurePageReloaded();
	    wait.until(stalenessOf(driver.findElement(By.className("nocover"))));
	    wait.until(presenceOfElementLocated(By.className("nocover")));
	    return this;
	  }
  
  @FindBy(css = "nav a[href $= '?go=profile']")
  private WebElement userProfileLink;

  @FindBy(css = "nav a[href $= '?go=users']")
  private WebElement userManagementLink;

  @FindBy(css = "nav a[href $= '?logout']")
  private WebElement logoutLink;
  
  @FindBy(css = "nav a[href $= '?go=add']")
  private WebElement movieAddLink;
  
  @FindBy(className = "movie_cover")
  public List <WebElement> addedMovies;
  
  @FindBy(id = "q")
  private WebElement searchMovieLink;
  
   
  @FindBy(id = "results")
  public WebElement movieNotFoundResult;
   
  
  
  public UserProfilePage clickUserProfilePage() {
    userProfileLink.click();
    return pages.userProfilePage;
  }

  public UserManagementPage clickUserManagementLink() {
    userManagementLink.click();
    return pages.userManagementPage;
  }
  
  public LoginPage clickLogoutLink() {
    logoutLink.click();
    wait.until(alertIsPresent()).accept();
    return pages.loginPage;
  }

  public InternalPage clickMovieLink(String deletedTitle) {
	  driver.findElement(By.partialLinkText(deletedTitle)).click();
	  return pages.moviePage;
	  }
  
  public MovieAddPage clickMovieAddLink() {
	    movieAddLink.click();
	    return pages.movieAddPage;
	  }

  public List <String> getMovieNames(){
	  	  for (WebElement movie:addedMovies){
		  List <String> movieNames = new ArrayList<String>();
		  movieNames.add(movie.getAttribute("title"));
	  }
	  return getMovieNames();  
  }
  
    
  public InternalPage searchMovie(String title) {
	  searchMovieLink.clear();
	  searchMovieLink.sendKeys(title+Keys.RETURN);
	  return this;
	  }
  
}
